//
//  ViewController.m
//  GetDataFromApache
//
//  Created by 移云 on 2019/10/8.
//  Copyright © 2019 admin. All rights reserved.
//

#import "ViewController.h"
#import "Person.h"
#import "Message.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self getPlistData];
    
    Person *personOne = [[Person alloc] init];
    personOne.name = @"猫爷爷的酱醋茶";
    personOne.age = 24;
    
    //重写description 获取更多信息
    NSLog(@"%@",personOne);
    
}

//从服务器获取plist 并解析plist
//一般服务器不会部署plist，因为这是IOS特有的文件
//一般保存本地也不用plist，用JSON格式更方便，也更容易多平台互通
- (void)getPlistData
{
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/videos.plist"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
    [request setValue:@"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Mobile Safari/537.36" forHTTPHeaderField:@"User-Agent"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (!connectionError)
        {
            //判断是否正常接受服务器放回的数据
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200 || httpResponse.statusCode ==304)
            {
              id plist = [NSPropertyListSerialization propertyListWithData:data options:0 format:0 error:NULL];
                NSLog(@"%@",plist);
                NSLog(@"%@",[plist class]);
                NSLog(@"%@",plist[0][@"name"]);
                
            }else{
                NSLog(@"服务器内部错误");
            }
            
        }else{
            NSLog(@"%@",connectionError);
        }
        
        
    }];
}

//获取网络数据 方式二  - 优势在于可以设置请求头
- (void)getDataModeB
{
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
    
    //默认缓存策略为0，超时时长为60s
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
    
    //可在此设置缓存方式 和超时时长
    /*
     NSURLRequestUseProtocolCachePolicy = 0,  //使用http协议缓存策略

     NSURLRequestReloadIgnoringLocalCacheData = 1,  //忽略本地缓存，重新加载缓存 - （实时更新）
     NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4,  //忽略本地和远程的缓存，重新加载
     NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,

     NSURLRequestReturnCacheDataElseLoad = 2,  //如果有缓存，返回缓存，如果没有，重新加载
     NSURLRequestReturnCacheDataDontLoad = 3,  //返回缓存，如果没有缓存，也不加载 - （没有网络）

     NSURLRequestReloadRevalidatingCacheData = 5,  //验证缓存，重新加载
     
     */
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
    
    //设置请求头
    [request setValue:@"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Mobile Safari/537.36" forHTTPHeaderField:@"User-Agent"];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
//        NSLog(@"%@",response);
        
        if (!connectionError)
        {
            //判断是否正常接受服务器放回的数据
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode == 200 || httpResponse.statusCode ==304)
            {
                //data - 二进制数据 是JSON 形式的字符串
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"%@",str);
                
                //JSON的反序列化 - 把JSON形式的字符串转换成OC中的对象
//                NSError *error;
//                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//                if (error)
//                {
//                    NSLog(@"解析JSON出错 --- %@",error);
//                    return;
//                }
                //操作JSON
//                NSLog(@"%@",json[@"message"]);
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                Message *msg = [Message messageWithDic:dic];
                NSLog(@"%@",msg);
               
                
                
            }else{
                NSLog(@"服务器内部错误");
            }
            
        }else{
            NSLog(@"%@",connectionError);
        }
        
        
        
    }];
}

 //获取网络数据 方式一  - 无法设置请求头，无法设置缓存，无法设置超时时长
- (void)getDataModeA
{
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
}




@end
